package com.ssm.websocket.config;

import org.springframework.stereotype.Component;
import org.springframework.util.CollectionUtils;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpServletRequest;
import javax.websocket.HandshakeResponse;
import javax.websocket.server.HandshakeRequest;
import javax.websocket.server.ServerEndpointConfig;
import java.util.List;
import java.util.Map;

/**
 * 业务场景中可能不能什么用户都可以进行访问WebSocket，所以需要进行鉴权和配置相关信息的功能！
 */
@Component
public class WebSocketServerConfig extends ServerEndpointConfig.Configurator {

    @Override
    public boolean checkOrigin(String originHeaderValue) { //实现鉴权效果，要重写方法
        //获取websocket的request对象
        ServletRequestAttributes servletRequestAttributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();

        //获取http的request对象
        HttpServletRequest request = servletRequestAttributes.getRequest();

        //校验逻辑

        return true; //校验通过
    }

    @Override
    public void modifyHandshake(ServerEndpointConfig sec,
                                HandshakeRequest request, HandshakeResponse response) {
        Map<String, List<String>> parameterMap = request.getParameterMap(); //获取WebSocket的所有请求参数
        List<String> erpList = parameterMap.get("erp"); //获取前端传递的erp相关参数信息(作为，每个连接的唯一标识 url?erp=xx)

        if(!CollectionUtils.isEmpty(erpList)) {
            //使用ServerEndpointConfig来进行相应的参数传递(此处将erp相关参数信息作为用户参数传递)
            sec.getUserProperties().put("erp", erpList.get(0)); //get(0), 一般请求参数只对应一个值
        }
    }
}
